package com.junjiao.util.java;

import java.math.BigDecimal;

/**
 * 一般数字处理工具类 
 *
 * @author jiaojun
 * @email:junjiao.j@gmail.com
 * @version:v0.2
 * @date:2012-12-26
 */
public class MathUtil {
	
	/**
	 * 四舍五入，并保留两位小数
	 * 
	 * @param i
	 * @return
	 */
	protected String round(double i) {
		BigDecimal b = new BigDecimal(i);
		double f = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return f + "";
	}

	/**
	 * 四舍五入，并保留两位小数
	 * 
	 * @param str
	 * @return
	 */
	protected String round(String str) {
		int num = 2;
		if (str.indexOf(".") > -1) {
			String str1 = str.substring(str.indexOf(".") + 1, str.indexOf(".")
					+ 1 + str.length() - (str.indexOf(".") + 1));
			int i = 0;
			if (str1.length() > num) {
				if (Integer.valueOf(str1.substring(num, num + 1)) > 4) {
					int val = 0;
					val = Integer.valueOf(str1.substring(0, num + 1))
							+ (10 - Integer.valueOf(str1
									.substring(num, num + 1)));
					if (String.valueOf(val).length() > (num + 1)) {
						i = 1;
						str1 = String.valueOf(val).substring(1, num + 1);
					} else {
						str1 = String.valueOf(val).substring(0, num);
					}
				} else {
					str1 = str1.substring(0, num);
				}
				if (str.indexOf(".") > 0) {
					String str2 = str.substring(0, str.indexOf("."));
					if (num > 0) {
						str = String.valueOf(Integer.valueOf(str2) + i) + "."
								+ str1;
					} else {
						str = String.valueOf(Integer.valueOf(str2) + i);
					}
				} else {
					if (num > 0) {
						str = String.valueOf(i) + "." + str1;
					} else {
						str = String.valueOf(i);
					}
				}
			} else if (str1.length() < num) {
				for (int n = 0; n < (num - str1.length()); n++) {
					str = str + "0";
				}
			}
		}
		return str;
	}
}
